import api from "../../utils/apiInstance"
import {
  getUserInfo
} from '../../utils/store';

const app = getApp();
const moment = app.moment
Page({
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,

    staffList: [],
    deptList: [],
    searchData: [],
    safetyIndexList: [],
    dept: '',
    staff: '',
    staffId: '',
    safeType: '',
    recDate: new Date().toISOString().substring(0, 10),
    bigSearchType: '',
    dataSourceList: ['班组', '部门', '公司'],
    rankings: ['第一名', '第二名', '第三名', '第四名', '第五名'],
    rankingIndex: '',
    addTypes: ['突出表现', '发现并抢险', '协助排查偷盗', '检举其他班组人员', '其他'],
    addTypeIndex: '',
    addScores: [1, 2, 3],
    addScoreIndex: '',
    dataSourceIndex: '',
    scoreIndexs: [{
        "id": 16,
        "label": "险兆事件"
      },
      {
        "id": 17,
        "label": "轻微事件"
      },
      {
        "id": 18,
        "label": "一般事故"
      },
    ],
    subInfos: [{
        "value": 0,
        "label": "三违教育"
      },
      {
        "value": 1,
        "label": "口头警告"
      },
      {
        "value": 2,
        "label": "通报批评"
      },
      {
        "value": 3,
        "label": "书面警告"
      },
      {
        "value": 4,
        "label": "严重书面警告"
      },
      {
        "value": 7,
        "label": "解除劳动合同"
      },
    ],
    addInfos: [{
        "value": 5,
        "label": "安全分享"
      },
      {
        "value": 6,
        "label": "通报表扬"
      },
    ],
    recInfoIndex: '',
    recInfo: '',
    scoreSub: '',
    fileList: [],
    fileNameList: [],
    pics: ['JPG', 'PNG', 'jpeg', 'jpg', 'png']
  },

  chooseFile() {
    var that = this;
    wx.chooseMessageFile({
      count: 1,
      type: 'all',
      async success(res) { // 将图片上传到服务器
        let tempFile = res.tempFiles[0];
        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload?name=' + tempFile.name, // 上传的服务器地址
          filePath: tempFile.path, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            let tempArray2 = [];
            tempArray2.push(tempFile.name);
            // 上传成功，做一些处理
            if (that.data.fileList.length != 0) {
              that.setData({
                fileList: that.data.fileList.concat(tempArray),
                fileNameList: that.data.fileNameList.concat(tempArray2),
              })
            } else {
              that.setData({
                fileList: tempArray,
                fileNameList: tempArray2
              })
            }
          }
        })
      }
    })
  },
  delFile(e) {
    wx.showModal({
      title: '删除文件',
      content: '确定要删除这个文件',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.fileList.splice(e.currentTarget.dataset.index, 1);
          this.data.fileNameList.splice(e.currentTarget.dataset.index, 1);

          this.setData({
            fileList: this.data.fileList,
            fileNameList: this.data.fileNameList
          })
        }
      }
    })
  },
  downFile(e) {
    var url = this.data.fileUrl + this.data.fileList[e.currentTarget.dataset.index];
    var suffix = url.substring(url.lastIndexOf(".") + 1);
    if (this.data.pics.includes(suffix)) {
      wx.previewImage({
        current: url, // 当前显示图片
        urls: [url] // 所有需预览的图片
      });
    } else {
      // 1. 下载文件
      wx.downloadFile({
        url: url,
        success: (res) => {
          const tempPath = res.tempFilePath;
          // 2. 保存到本地（可选）
          wx.saveFile({
            tempFilePath: tempPath,
            success: (savedRes) => {
              // 3. 打开文档
              wx.openDocument({
                filePath: savedRes.savedFilePath,
                fileType: suffix // 根据后缀指定类型
              });
            }
          });
        }
      });
    }
  },

  submitForm(e) {
    wx.showLoading({
      title: '提交中',
      mask: true
    });
    const formData = e.detail.value;
    var errMsg = "";
    if (!this.data.staffId) {
      errMsg = errMsg + "员工不能为空;";
    }
    if (!this.data.dataSourceIndex) {
      errMsg = errMsg + "数据来源不能为空;";
    }
    if (!this.data.safeType) {
      errMsg = errMsg + "安全指标不能为空;";
    } else if (this.data.safeType == 16 || this.data.safeType == 17 || this.data.safeType == 18) {
      if (!this.data.scoreIndex) {
        errMsg = errMsg + "事件类型不能为空;";
      }
    } else if (this.data.safeType == 21) {
      if (!this.data.rankingIndex) {
        errMsg = errMsg + "名次不能为空;";
      }
      if (!this.data.addScoreIndex) {
        errMsg = errMsg + "加分值不能为空;";
      }
    } else if (this.data.safeType == 22) {
      if (!this.data.addTypeIndex) {
        errMsg = errMsg + "加分类型不能为空;";
      }
      if (!this.data.addScoreIndex) {
        errMsg = errMsg + "加分值不能为空;";
      }
    }
    if (!this.data.recInfoIndex) {
      errMsg = errMsg + "处罚/奖励通报不能为空;";
    }
    if (!formData.recDescribe) {
      errMsg = errMsg + "事件记录不能为空;";
    }
    if (errMsg.length > 0) {
      wx.hideLoading()
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }
    formData.staffId = this.data.staffId;
    formData.dataSource = this.data.dataSourceIndex ? Number(this.data.dataSourceIndex) + 1 : '';
    formData.safeType = this.data.safeType;
    formData.scoreIndex = this.data.scoreIndex ? this.data.scoreIndex : this.data.safeType;
    formData.teamAddType = this.data.safeType == 21 ? Number(this.data.rankingIndex) + 1 : this.data.safeType == 22 ? Number(this.data.addTypeIndex) + 1 : '';
    formData.recInfo = this.data.recInfo;
    formData.scoreSub = this.data.scoreSub;
    formData.scoreAdd = this.data.addScoreIndex ? Number(this.data.addScoreIndex) + 1 : '';
    formData.createSapId = getUserInfo().siocSapNo;
    formData.createBy = getUserInfo().siocCnName;
    formData.createEmail = getUserInfo().email;

    if (this.data.fileList.length != 0) {
      formData.fileUrls = this.data.fileList.join(",");
    }
    console.log('form发生了submit事件，携带数据为：', formData);

    var that = this;
    // 向服务器提交表单数据
    wx.request({
      url: that.data.baseUrl + '/personSafety',
      method: 'POST',
      data: formData,
      success: function (res) {
        wx.hideLoading()
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/menu/menu'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        wx.hideLoading()
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },

  doBigSearchShow(e) {
    const searchType = e.currentTarget.dataset.type;
    const searchData = searchType == 'dept' ? this.data.deptList : this.data.staffList;
    if (searchData.length == 0) {
      wx.showToast({
        title: '请先选择部门',
        icon: 'none'
      });
      return;
    }
    this.setData({
      bigSearchType: searchType,
      bigSearchShow: true,
      searchData: searchData
    })
  },
  searchSelect(e) {
    if ('dept' == this.data.bigSearchType) {
      this.setData({
        staff: '',
        staffId: '',
        staffList: [],
        dept: e.detail.name ? e.detail.name : ''
      });
      if (e.detail.name) {
        this.getStaffs(e.detail.name);
      }
    }
    if ('staff' == this.data.bigSearchType) {
      this.setData({
        staff: e.detail.name ? e.detail.name : '',
        staffId: e.detail.name ? e.detail.id : '',
      });
    }
    this.setData({
      bigSearchShow: false,
    })
  },
  DateChange: function (e) {
    this.setData({
      recDate: e.detail.value
    })
  },
  dsChange(e) {
    this.setData({
      dataSourceIndex: e.detail.value
    })
  },
  safetyChange(e) {
    this.setData({
      scoreIndex: '',
      rankingIndex: '',
      addTypeIndex: '',
      recInfoIndex: '',
      recInfo: '',
      addScoreIndex: '',
      scoreSub: '',
      safetyIndex: e.detail.value,
      safeType: this.data.safetyIndexList[e.detail.value].id
    })
  },
  scoreChange(e) {
    this.setData({
      scoresIndex: e.detail.value,
      scoreIndex: this.data.scoreIndexs[e.detail.value].id
    })
  },
  rankingChange(e) {
    this.setData({
      rankingIndex: e.detail.value,
    })
  },
  addTypeChange(e) {
    this.setData({
      addTypeIndex: e.detail.value,
    })
  },
  addScoreChange(e) {
    this.setData({
      addScoreIndex: e.detail.value,
    })
  },
  recInfoChange(e) {
    const tempRecInfo = this.data.safeType == 21 || this.data.safeType == 22 ? this.data.addInfos[e.detail.value].value : this.data.subInfos[e.detail.value].value;
    let tempScoreSub = '';
    if (tempRecInfo == 1 || tempRecInfo == 0) {
      tempScoreSub = 1;
    }
    if (tempRecInfo == 2) {
      tempScoreSub = 3;
    }
    if (tempRecInfo == 3) {
      tempScoreSub = 6;
    }
    if (tempRecInfo == 4 || tempRecInfo == 7) {
      tempScoreSub = 12;
    }
    this.setData({
      recInfoIndex: e.detail.value,
      recInfo: tempRecInfo,
      scoreSub: tempScoreSub
    })
  },
  async getSafetyIndex() {
    const result = await api.get("/personSafety/getSafetyIndex");
    this.setData({
      safetyIndexList: result.data
    })
  },

  async onLoad() {
    this.getDepts();
    this.getSafetyIndex();
  },

  async getStaffs(dept) {
    const result = await api.get("/staffInfo/wx/getStaffByDept2", {
      "dept": dept
    });
    result.data.forEach(item => {
      this.data.staffList.push({
        name: item.staffName,
        id: item.id
      });
    });
  },

  async getDepts() {
    const result = await api.get("/deptInfo/wx/getAllDept");
    result.data.forEach(item => {
      this.data.deptList.push({
        name: item
      });
    });
  },
})